package com.yifeng.repo.base.utils.file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.zip.*;

/**
 * ZIP处理类
 * created by zyh
 */
public class ZipHelper {
    private static final int BUFFER = 1024;

    /**
     * 压缩文件(默认包含最外层目录)
     * @param srcFile    源文件
     * @param destFile   压缩文件
     */
    public static void compress(File srcFile, File destFile) {
        compress(srcFile, destFile.getPath(), false);
    }

    /**
     * 压缩文件(默认包含最外层目录)
     * @param srcFile    源文件
     * @param destPath   压缩路径
     */
    public static void compress(File srcFile, String destPath) {
        compress(srcFile, destPath, false);
    }

    /**
     * 压缩文件
     * @param srcFile    源文件
     * @param destPath   压缩路径
     */
    public static void compress(File srcFile, String destPath, boolean excludeOuter) {
        // 1、check file
        if (!srcFile.exists()) {
            throw new RuntimeException("srcFile does not exist, path= " + srcFile.getAbsolutePath());
        }
        File targetFile = new File(destPath);
        if (targetFile.exists()) {
            throw new RuntimeException("targetFile exist, path= " + targetFile.getAbsolutePath());
        }
        // 2、compress file
        try {
            ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(targetFile.toPath()), Charset.defaultCharset());
            compressFile(srcFile, zipOutputStream, "", excludeOuter);
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void compressFile(File file, ZipOutputStream output, String childPath, boolean excludeOuter){
        FileInputStream input = null;
        childPath = excludeOuter ? childPath + (childPath.length() == 0 ? "" : "/") :
                childPath + (childPath.length() == 0 ? "" : "/") + file.getName();
        try {
            // if dir
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                // if empty
                if(files == null || files.length == 0) {
                    output.putNextEntry(new ZipEntry(childPath + "/"));
                } else {
                    // if not empty
                    for (File f : files) {
                        compressFile(f, output, childPath, false);
                    }
                }
            } else {
                // if file
                output.putNextEntry(new ZipEntry(childPath));
                input = new FileInputStream(file);
                int readLen;
                byte[] buffer = new byte[BUFFER];
                while ((readLen = input.read(buffer)) != -1) {
                    output.write(buffer, 0, readLen);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 解压文件
     * @param srcFile  源文件
     * @param destFile 解压文件
     */
    public static void decompress(File srcFile, File destFile) {
        decompress(srcFile, destFile.getPath());
    }

    /**
     * 解压文件
     * @param srcFile  源文件
     * @param destPath 解压路径
     */
    public static void decompress(File srcFile, String destPath) {
        try {
            CheckedInputStream cis = new CheckedInputStream(Files.newInputStream(srcFile.toPath()), new CRC32());
            ZipInputStream zis = new ZipInputStream(cis, Charset.defaultCharset());
            decompress(new File(destPath), zis);
            zis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void decompress(File destFile, ZipInputStream zis) throws Exception {
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String dir = destFile.getPath() + File.separator + entry.getName();
            File dirFile = new File(dir);
            fileProbe(dirFile);
            if (entry.isDirectory()) {
                dirFile.mkdirs();
            } else {
                decompressFile(dirFile, zis);
            }
            zis.closeEntry();
        }
    }

    private static void fileProbe(File dirFile) {
        File parentFile = dirFile.getParentFile();
        if (!parentFile.exists()) {
            fileProbe(parentFile);
            parentFile.mkdir();
        }
    }

    private static void decompressFile(File destFile, ZipInputStream zis) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(destFile.toPath()));
        int count;
        byte[] data = new byte[BUFFER];
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            bos.write(data, 0, count);
        }
        bos.close();
    }
}